<!--<template>-->
<!--  <div class="wrapper">-->
<!--    &lt;!&ndash; header部分 &ndash;&gt;-->
<!--    <header>-->
<!--      <p id="tit">用户登录</p>-->
<!--      <div class="user-type-tabs">-->
<!--        <div-->
<!--          class="tab customer-tab active"-->
<!--          id="customerTab"-->
<!--          @click="switchUserType('customer')"-->
<!--        >-->
<!--          客户登录-->
<!--        </div>-->
<!--        <div-->
<!--          class="tab business-tab"-->
<!--          id="businessTab"-->
<!--          @click="switchUserType('business')"-->
<!--        >-->
<!--          商家登录-->
<!--        </div>-->
<!--      </div>-->
<!--    </header>-->
<!--    &lt;!&ndash; 表单部分 &ndash;&gt;-->
<!--    <ul class="form-box">-->
<!--      <li>-->
<!--        <div class="title">手机号码：</div>-->
<!--        <div class="content">-->
<!--          <input type="text" v-model="userId" placeholder="手机号码" />-->
<!--        </div>-->
<!--      </li>-->
<!--      <li>-->
<!--        <div class="title">密码：</div>-->
<!--        <div class="content">-->
<!--          <input type="password" v-model="password" placeholder="密码" />-->
<!--        </div>-->
<!--      </li>-->
<!--    </ul>-->
<!--    <div class="button-login">-->
<!--      <button @click="login">登陆</button>-->
<!--    </div>-->
<!--    <div class="button-register">-->
<!--      <button @click="register">去注册</button>-->
<!--    </div>-->
<!--    &lt;!&ndash; 底部菜单部分 &ndash;&gt;-->
<!--    <Footer></Footer>-->
<!--  </div>-->
<!--</template>-->
<!--<script setup>-->
<!--import { ref } from "vue";-->
<!--import { useRouter } from "vue-router";-->
<!--import axios from "axios";-->
<!--import qs from "qs";-->
<!--import Footer from "../components/Footer.vue";-->

<!--const router = useRouter();-->
<!--const userId = ref("");-->
<!--const password = ref("");-->
<!--const type = ref("customer"); // 默认用户类型为客户-->
<!--// 切换用户类型时，更新type的值-->

<!--const login = async () => {-->
<!--  if (userId.value === "") {-->
<!--    alert("手机号码不能为空！");-->
<!--    return;-->
<!--  }-->
<!--  if (password.value === "") {-->
<!--    alert("密码不能为空！");-->
<!--    return;-->
<!--  }-->
<!--  if (type.value === "customer") {-->
<!--    try {-->
<!--      const response = await axios.post(-->
<!--        "auth",-->
<!--        qs.stringify({-->
<!--          userId: userId.value,-->
<!--          password: password.value,-->
<!--        })-->
<!--      );-->

<!--      const user = response.data;-->
<!--      if (!user) {-->
<!--        alert("用户名或密码不正确！");-->
<!--      } else {-->
<!--        // sessionstorage has capacity limits, so we don't store userImg to prevent data overflow-->
<!--        user.userImg = "";-->
<!--        sessionStorage.setItem("user", JSON.stringify(user));-->
<!--        router.go(-1);-->
<!--      }-->
<!--    } catch (error) {-->
<!--      console.error(error);-->
<!--    }-->
<!--  } else {-->
<!--    try {-->
<!--      const response = await axios.post(-->
<!--        "BusinessController/login", // 商家登录接口-->
<!--        qs.stringify({-->
<!--          businessId: userId.value, // 使用商家ID登录-->
<!--          password: password.value,-->
<!--        })-->
<!--      );-->

<!--      const business = response.data;-->
<!--      if (!business) {-->
<!--        alert("商家账号或密码不正确！");-->
<!--      } else {-->
<!--        // 存储商家信息到sessionStorage-->
<!--        sessionStorage.setItem("business", JSON.stringify(business));-->
<!--        sessionStorage.setItem("user", JSON.stringify({}));-->
<!--        // 跳转到商家管理页面-->
<!--        router.push({ path: "/BusinessEnd" });-->
<!--      }-->
<!--    } catch (error) {-->
<!--      console.error("商家登录失败:", error);-->
<!--      alert("登录失败，请稍后重试");-->
<!--    }-->
<!--  }-->
<!--};-->

<!--const register = () => {-->
<!--  router.push({-->
<!--    path: "/register",-->
<!--  });-->
<!--};-->
<!--const switchUserType = (newType) => {-->
<!--  const customerTab = document.getElementById("customerTab");-->
<!--  const businessTab = document.getElementById("businessTab");-->

<!--  if (newType === "customer") {-->
<!--    customerTab.classList.add("active");-->
<!--    businessTab.classList.remove("active");-->
<!--    type.value = "customer"; // 更新type的值为客户-->
<!--    document.getElementById("tit").innerText = "客户登录"; // 更新标题-->
<!--  } else {-->
<!--    customerTab.classList.remove("active");-->
<!--    businessTab.classList.add("active");-->
<!--    type.value = "business"; // 更新type的值为商家-->
<!--    document.getElementById("tit").innerText = "商家登录"; // 更新标题-->
<!--  }-->
<!--};-->
<!--</script>-->

<template>
  <div class="wrapper">
    <!--顶部栏-->
    <header>
      <p>登录</p>
    </header>
    <!-- logo-->
    <div class="logo">
      <i class="fa-solid fa-circle-user fa-3x"></i>
    </div>
    <!-- 切换身份-->
    <div class="user-type-tabs">
      <div
          class="tab customer-tab active"
          id="customerTab"
          @click="switchUserType('customer')"
      >
        用户登录
      </div>
      <div
          class="tab business-tab"
          id="businessTab"
          @click="switchUserType('business')"
      >
        商家登录
      </div>
    </div>

    <!-- 错误提示信息 -->
    <div v-if="errorMessage" class="error-message">
      <p>{{ errorMessage }}</p>
    </div>

    <!-- 登录表单-->
    <div class="login">
      <ul class="form-box">
        <li>
          <div class="title">账号：</div>
          <div class="content">
            <input type="text" v-model="userId" placeholder="账号" @keyup.enter="handleLogin"/>
          </div>
        </li>
        <li>
          <div class="title">密码：</div>
          <div class="content">
            <input type="password" v-model="password" placeholder="密码" @keyup.enter="handleLogin"/>
          </div>
        </li>
        <li class="remember-me">
          <div class="content">
            <label class="checkbox-container">
              <input type="checkbox" v-model="rememberMe" @keyup.enter="handleLogin"/>
              <span class="checkmark"></span>
              记住我
            </label>
          </div>
        </li>
      </ul>

      <!-- 商家提示信息 -->
      <div v-if="userType === 'business'" class="business-tip">
        <p>商家身份需要用户通过申请获取</p>
      </div>

      <!-- 登录按钮 -->
      <div class="button-login">
        <button @click="handleLogin" :disabled="loading">
          {{ loading ? '登录中...' : '登录' }}
        </button>
      </div>
      <!-- 注册按钮 - 商家登录时隐藏 -->
      <div v-if="userType !== 'business'" class="button-register">
        <button @click="handleRegister">注册</button>
      </div>
    </div>

    <!-- 管理员登录按钮 -->
    <div class="admin-login-section">
      <button class="admin-login-btn" @click="handleAdminLogin">
        <i class="fa-solid fa-user-shield"></i>
        管理员登录
      </button>
    </div>

    <!--  底部菜单-->
    <Footer></Footer>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from  '@/stores/auth'
import { authAPI } from '@/api/auth.js'
import { userAPI } from '@/api/user.js'
import Footer from "@/components/Footer.vue";
import {setSessionStorage} from "@/common";

// 响应式数据
const userId = ref('')
const password = ref('')
const rememberMe = ref(false)
const userType = ref('customer') // 默认用户登录
const loading = ref(false)
const errorMessage = ref('')
const router = useRouter()
const authStore = useAuthStore()
const ROLES = {
  USER: 'USER',
  BUSINESS: 'BUSINESS',
  ADMIN: 'ADMIN'
}


// 权限映射
const PERMISSIONS = {
  CUSTOMER: 'USER', // 用户权限
  BUSINESS: 'BUSINESS' // 商家权限
}

// 切换用户类型
const switchUserType = (type) => {
  userType.value = type
  // 切换用户类型时清空错误信息
  errorMessage.value = ''

  // 更新标签页样式
  const customerTab = document.getElementById('customerTab')
  const businessTab = document.getElementById('businessTab')

  if (type === 'customer') {
    customerTab.classList.add('active')
    businessTab.classList.remove('active')
  } else {
    businessTab.classList.add('active')
    customerTab.classList.remove('active')
  }
}

// 验证权限
const validatePermission = (userAuthorities, requiredUserType) => {
  if (!userAuthorities || !Array.isArray(userAuthorities)) {
    return false
  }

  const requiredPermission = requiredUserType === 'customer'
      ? PERMISSIONS.CUSTOMER
      : PERMISSIONS.BUSINESS

  return userAuthorities.some(auth => {
    if (auth.name && auth.name === requiredPermission) {
      return true
    }
    return false
  })
}

// 处理登录
const handleLogin = async () => {
  // 重置错误信息
  errorMessage.value = ''

  // 简单的表单验证
  if (!String(userId.value).trim()) {
    errorMessage.value = '请输入账号'
    // 清空密码栏
    password.value = ''
    return
  }

  if (!String(password.value).trim()) {
    errorMessage.value = '请输入密码'
    // 清空密码栏
    password.value = ''
    return
  }

  loading.value = true

  try {
    // 1. 发送登录请求获取token
    const loginCredentials = {
      username: userId.value,
      password: password.value,
      rememberMe: rememberMe.value
    }

    const loginResponse = await authAPI.login(loginCredentials)

    if (!loginResponse.data || !loginResponse.data.id_token) {
      const errorMsg = '登录失败'
      throw new Error(errorMsg)
    }

    // 2. 保存登录信息到store
    const authResult = await authStore.login(loginResponse)

    // 3. 使用token获取当前用户信息（包含权限信息）
    const userResponse = await userAPI.getActualUser()

    if (!userResponse.data) {
      throw new Error('获取用户信息失败')
    }

    // 4. 验证用户权限是否符合选择的登录类型
    const userAuthorities = userResponse.data.authorities
    const hasRequiredPermission = validatePermission(userAuthorities, userType.value)

    if (!hasRequiredPermission) {
      const requiredType = userType.value === 'customer' ? '用户' : '商家'
      throw new Error(`您没有${requiredType}权限，请使用正确的账号登录`)
    }

    if (!authResult.success) {
      throw new Error(authResult.message || '登录信息保存失败')
    }

    // 5. 登录成功，跳转到对应页面
    setSessionStorage("userId", userResponse.data.id)
    setSessionStorage("userAuthorities",userResponse.data.authorities)
    // 设置用户角色


    // 根据用户类型跳转到对应页面
    if (userType.value === 'business') {
      const userRole = ROLES.BUSINESS
      sessionStorage.setItem('userRole', userRole)
      // console.log("user:",userRole)
      // 商家用户跳转到商家后台
      router.push('/BusinessEnd')
    } else {
      const userRole = ROLES.USER
      sessionStorage.setItem('userRole', userRole)
      // console.log("user:",userRole)
      // 普通用户跳转到首页
      router.push('/')
    }

  } catch (error) {
    console.error('登录失败:', error)
    errorMessage.value ='登录失败，请检查账号密码'

    // 登录失败时清空密码栏
    password.value = ''

    // 调用登出清理token等
    authStore.logout()

  } finally {
    loading.value = false
  }
}

// function getUserRole(authorities) {
//   if (!authorities || !Array.isArray(authorities)) return ROLES.USER;
//
//   const authorityNames = authorities.map(auth =>
//       typeof auth === 'string' ? auth : (auth.name || auth.authority)
//   );
//
//   if (authorityNames.includes('ADMIN')) return ROLES.ADMIN;
//   if (authorityNames.includes('BUSINESS')) return ROLES.BUSINESS;
//   return ROLES.USER;
// }

// 处理注册
const handleRegister = () => {
  if (userType.value === 'customer') {
    router.push('/register')
  }
}

// 处理管理员登录
const handleAdminLogin = () => {
  // 跳转到管理员登录页面或切换为管理员登录模式
  router.push('/admin-login')
  // 或者可以在这里切换登录模式
  // switchUserType('admin')
}

// 页面加载时检查是否有记住的用户
onMounted(() => {
  const savedUserId = sessionStorage.getItem('userId')
  if (savedUserId) {
    userId.value = savedUserId
    rememberMe.value = true
  }

  // 检查是否已经登录
  const token = sessionStorage.getItem('token')
  const isLoggedIn = !!token

  if (isLoggedIn) {
    console.log('检测到已登录用户访问登录页')

    const redirect = router.currentRoute.value.query.redirect

    if (redirect && redirect !== '/login') {
      router.push(redirect)
    } else {
      router.push('/index')
    }
  }
})
</script>

<style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097ff;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

header p {
  font-size: 1.5rem;
  font-weight: 600;
  letter-spacing: 1px;
}

/****************** logo部分 ******************/
.logo {
  flex: 0.15;
  margin-top: 12vw;
  display: flex;
  justify-content: center;
  align-items: center;
}

.logo i {
  color: gray;
}

/****************** 切换身份部分 ******************/
.user-type-tabs {
  display: flex;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50px;
  padding: 4px;
  margin: 0 3vw;
}

.tab {
  flex: 1;
  text-align: center;
  padding: 10px;
  border-radius: 50px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: rgb(245, 247, 249);
}

.tab.active {
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.customer-tab.active {
  color: var(--customer);
}

.business-tab.active {
  color: var(--business);
}

/****************** 错误提示信息 ******************/
.error-message {
  text-align: center;
  padding: 2vw 3vw;
  margin-top: 2vw;
  animation: fadeIn 0.3s ease;
}

.error-message p {
  font-size: 3.5vw;
  color: #ff4d4f;
  background-color: #fff2f0;
  padding: 3vw;
  border-radius: 8px;
  border-left: 4px solid #ff4d4f;
  margin: 0;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/****************** 表单部分 ******************/
.login {
  flex:0.5;
}

.login .form-box {
  width: 100%;
  margin-top: 6vw;
}

.login .form-box li {
  box-sizing: border-box;
  padding: 4vw 3vw 0 3vw;
  display: flex;
  align-items: center;
}

.login .form-box li .title {
  flex: 0 0 13vw;
  font-size: 4vw;
  font-weight: 800;
  color: #666;
}

.login .form-box li .content {
  flex: 1;
}

.login .form-box li .content input {
  border: gray 0.5px solid;
  border-radius: 8px;
  outline: none;
  width: 100%;
  height: 8vw;
  font-size: 4vw;
}

.login .form-box li .content input:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
  outline: none;
}

.remember-me {
  margin-top: 2vw;
}

.checkbox-container {
  display: flex;
  align-items: center;
  justify-content: right;
  cursor: pointer;
  font-size: 3.8vw;
  color: #666;
  user-select: none;
}

.checkbox-container input {
  display: none;
}

.checkmark {
  width: 4vw;
  height: 4vw;
  border: 2px solid #ddd;
  border-radius: 3px;
  margin-right: 2vw;
  position: relative;
  transition: all 0.3s ease;
}

.checkbox-container input:checked + .checkmark {
  background-color: #0097ff;
  border-color: #0097ff;
}

.checkbox-container input:checked + .checkmark::after {
  content: '';
  position: absolute;
  left: 1vw;
  top: 0.2vw;
  width: 1vw;
  height: 2vw;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

/****************** 商家提示信息 ******************/
.business-tip {
  text-align: center;
  padding: 2vw 3vw;
  margin-top: 2vw;
}

.business-tip p {
  font-size: 3.5vw;
  color: #ff6b6b;
  background-color: #fff5f5;
  padding: 2vw;
  border-radius: 8px;
  border-left: 4px solid #ff6b6b;
}

/****************** 登录注册按钮 ******************/
.login .button-login {
  width: 100%;
  box-sizing: border-box;
  padding: 4vw 3vw 0 3vw;
}

.login .button-login button {
  width: 100%;
  height: 10vw;
  font-size: 3.8vw;
  font-weight: 700;
  color: #fff;
  background-color: #38ca73;
  border-radius: 4px;
  border: none;
  outline: none;
  transition: all 0.3s ease;
}

.login .button-login button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.login .button-register {
  width: 100%;
  box-sizing: border-box;
  padding: 4vw 3vw 0 3vw;
}

.login .button-register button {
  width: 100%;
  height: 10vw;
  font-size: 3.8vw;
  font-weight: 700;
  color: #666;
  background-color: #eee;
  border: solid 1px #ddd;
  border-radius: 4px;
  border: none;
  outline: none;
}

/****************** 管理员登录按钮 ******************/
.admin-login-section {
  flex: 0.1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 3vw;
}

.admin-login-btn {
  background: transparent;
  border: 1px solid #ddd;
  color: #666;
  padding: 2vw 4vw;
  border-radius: 20px;
  font-size: 3.5vw;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 2vw;
}

.admin-login-btn:hover {
  background-color: #f5f5f5;
  border-color: #0097ff;
  color: #0097ff;
}

.admin-login-btn i {
  font-size: 4vw;
}
</style>